package com.hzqy.commons.utils;

import java.util.HashMap;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hzqy.web.login.LogInfo;
import com.hzqy.web.vo.wx_tv.WsSessionVo;

public class CommonsMessage {
	private static final Logger LOG = LoggerFactory.getLogger(CommonsMessage.class);
	private static HashMap<String,WsSessionVo> cacheHash = new HashMap<String,WsSessionVo>(); //key为业务账号,value为机顶盒session
	private static HashMap<String,String> cacheSessionIdHash = new HashMap<String,String>(); //key为session.getId(),value为业务账号
	
	/**
	 * 将机顶盒session存入缓存
	 * @param session 机顶盒的session
	 * @param serverId 机顶盒的业务账号
	 * @return
	 */
	public static void addCache(WsSessionVo wsSessionVo,String serverId) {
		cacheHash.put(serverId, wsSessionVo);
		cacheSessionIdHash.put(wsSessionVo.getSession().getId(), serverId);
	}
	
	public static HashMap<String,WsSessionVo> getCache() {
		return cacheHash;
	}
	
	/**
	 * 通过业务账号获取机顶盒的session
	 * @param serverId
	 * @return
	 */
	public static WsSessionVo getStbSessionFromCache(String serverId) {
		return cacheHash.get(serverId);
	}
	
	/**
	 * 通过业务账号判定机顶盒session是否存在缓存中
	 * @param serverId
	 * @return
	 */
	public static boolean isExistStbSession(String serverId) {
		return cacheHash.get(serverId)!=null?true:false;
	}
	
	/**
	 * 移除缓存中的内容通过session
	 * @param session
	 */
	public static void removeCacheByStbSession(Session session) {
		String serverId = cacheSessionIdHash.remove(session.getId());
		cacheHash.remove(serverId);
		
		String logStr = "{"+serverId + "}{remove}{}{}{resolution}{areaId}{partner}";
		LogInfo logInfo = new LogInfo();
		logInfo.UrlLog(logStr);
	}
	
	/**
	 * 通过sessionId得到业务账号
	 * @param sessionId
	 * @return
	 */
	public static String getServerIdBySessionId(String sessionId) {
		return cacheSessionIdHash.get(sessionId);
	}
	
	/**
	 * 移除缓存中的内容通过业务账号
	 * @param session
	 */
	public static void removeCacheByServerId(String serverId) {
		WsSessionVo wsSessionVo = cacheHash.remove(serverId);
		cacheSessionIdHash.remove(wsSessionVo.getSession().getId());
	}
	
	public static void send(Session session,String message) {
		RemoteEndpoint.Basic remote2 = session.getBasicRemote();
		try {
			remote2.sendText(message);
		} catch (Exception e) {
			LOG.error("发送信息异常：",e);
		}
	}
}
